package cn.tradewin.pmp.pages.test;

import org.apache.tapestry5.PersistenceConstants;
import org.apache.tapestry5.ValidationException;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Log;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.slf4j.Logger;

public class MoreValidation {
	
	@Persist(PersistenceConstants.FLASH)
	private String firstName;

	@Log
	public String getFirstName() {
		return firstName;
	}

	@Log
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	@Persist(PersistenceConstants.FLASH)
	private Integer luckyNumber;
	
	

	// Generally useful bits and pieces
	@Log
	public Integer getLuckyNumber() {
		return luckyNumber;
	}

	@Log
	public void setLuckyNumber(Integer luckyNumber) {
		this.luckyNumber = luckyNumber;
	}

	@Component(id = "inputs")
	private Form form;
	
	@Inject
	Logger log;
	
	

	// The code
	@Log
	void onValidateFromFirstName(String value) throws ValidationException {

		// Error if doesn't contain letters only.

		if (value != null) {
			if (!value.matches("[A-Za-z]+")) {
				throw new ValidationException(
						"First Name must contain letters only");
			}
		}

	}

	@Log
	void onValidateFromLuckyNumber(Integer value) throws ValidationException {

		// Error if number 13 chosen.

		if (value != null) {
			if (value.equals(13)) {
				throw new ValidationException(
						"Sorry, but 13 is not a lucky number.");
			}
		}

	}

	/**
	 * Cross-form validation goes in here.
	 */
	@Log
	void onValidateFromInputs() {
		int i = 10/0;
		log.debug("1111");
		// Error if neither chosen.

		if (firstName == null && luckyNumber == null) {
			form.recordError("Please specify first name or lucky number.");
		}
		
		log.debug("22222");

		// Error if both chosen.

		if (firstName != null && luckyNumber != null) {
			form.recordError("Please do not specify both.");
		}
		log.debug("3333");
	}

}
